const express = require('express');

const chatModel = require('../modules/chat_tab');
const userModel = require('../modules/user_tab');
const chatRouter = express.Router()
const Sequelize = require('sequelize')
const Op = Sequelize.Op



chatRouter.get('/search', async (req, res, next) => {
    try {
        const page = parseInt(req.query.pageNum) || 1;
        const pageSize = parseInt(req.query.pageSize) || 10;
        const offset = (page - 1) * pageSize;
        const { content, nickname } = req.query;
        const sortFieldName = req.query.sortFieldName;
        const sortOrder = req.query.sortOrder || 'DESC';
        const order = [];
        let where = {
            is_delete: 0
        };
        
        order.push([sortFieldName, sortOrder]);

        if (content) {
            where.content = {
                [Op.like]: `%${content}%`
            };
        }

        if (nickname) {
            where[Op.or] = [
                { '$user1.nickname$': { [Op.like]: `%${nickname}%` } },
                { '$user2.nickname$': { [Op.like]: `%${nickname}%` } }
            ];
        }

        const chats = await chatModel.findAll({
            raw: true,
            offset,
            limit: pageSize,
            order,
            where,
            include: [
                { 
                    model: userModel,
                    as: 'user1', 
                    attributes: ['nickname'],
                    where: { is_delete: 0 }
                },
                {
                    model: userModel,
                    as: 'user2',
                    attributes: ['nickname'],
                    where: { is_delete: 0 }
                }
            ]
        });

        res.json({
            code: 1,
            msg: '请求成功',
            data: chats,
            total: chats.length
        });
    } catch (err) {
        next(err);
    }
});
//根据id删除，假删除
chatRouter.post('/delete/one',async(req,res,next) => {
    try {
        const { chat_id } = req.query;
        const chat = await chatModel.findOne({ where: { chat_id, is_delete:0 } });
        await chat.update({ is_delete:1 });
        res.json({
          code: 1,
          msg: '请求成功',
        });
      } catch (err) {
        next(err);
      }
})
//批量删除，假删除
chatRouter.post('/delete/amount',async(req,res,next) => {
    try {
        const { chats } = req.query;
        chats.forEach(async (item) => {
          const chat = await chatModel.findOne({ where: { chat_id:item.chat_id, is_delete:0 } });
          await chat.update({ is_delete:1 });
        })
        res.json({
          code:1,
          msg:'请求成功'
        })
      } catch (err) {
        next(err);
      }
})
//根据id查看聊天记录详情
chatRouter.get('/detail',async(req,res,next) => {
    try{
        const { chat_id } = req.query
        const chat = await chatModel.findOne({
            where:{chat_id,is_delete:0},
            include: [
                { model: userModel, as: 'user1',where:{is_delete:0} },
                { model: userModel, as: 'user2' ,where:{is_delete:0}}
              ]
        })
        res.json({
            code:1,
            msg:'请求成功',
            data:chat
        })
    }catch(err){
        next(err)
    }
})
//查询聊天的人以及记录
chatRouter.get('/all',async(req,res,next) => {
    try{
        const { user1_id } = req.query;
        // 找到每个 user2_id 对应的最新的 chat_id
        const latestChatIds = await chatModel.findAll({
            attributes: [
                [Sequelize.fn('MAX', Sequelize.col('chat_id')), 'latest_chat_id']
            ],
            where: {
                user1_id: user1_id
            },
            group: ['user2_id']
        });
        // 提取最新的 chat_id，构建查询条件
        const latestChatIdsArray = latestChatIds.map(chat => chat.dataValues.latest_chat_id);
        // 查询对应的聊天记录
        const chatRecords = await chatModel.findAll({
            where: {
                [Op.and]: [
                    { user1_id: user1_id },
                    { chat_id: { [Op.in]: latestChatIdsArray } }
                ]
            },
            include: [
                { model: userModel, as: 'user1' },
                { model: userModel, as: 'user2' }
            ]
        });
        res.json({
            code:1,
            msg:'请求成功',
            data:chatRecords
        })
    }catch(err){
        next(err)
    }
})
//根据id查找聊天记录
chatRouter.get('/user',async(req,res,next) => {
    try{
        const { user1_id,user2_id } = req.query
        const messages = await chatModel.findAll({
            raw:true,
            where:{
                is_delete:0,
                user1_id:{[Op.in]:[user1_id,user2_id]},
                user2_id:{[Op.in]:[user1_id,user2_id]}
            },
            include: [
                { model: userModel, as: 'user1' ,attributes:['avatar']},
                { model: userModel, as: 'user2' ,attributes:['avatar']}
            ],
            order:[
                [
                    "create_time",
                    "ASC"
                ]
            ]
        })
        res.json({
            code:1,
            msg:'请求成功',
            data:messages
        })
    }catch(err){
        next(err)
    }
})
// 错误处理中间件
chatRouter.use((err, req, res, next) => {

    res.status(500).json({
      code: 0,
      msg: '服务器内部错误',
    });
  });

module.exports = chatRouter